// 获取接口基础URL
const apiUrl = process.env.VUE_APP_BRACELET_API;

// 用于处理请求的统一函数，这里封装了基本的请求配置等操作
const requestHandler = (url, method, params, contentType) => {
    const token = uni.getStorageSync('access_token');
    const refreshToken = uni.getStorageSync('refreshToken');
    return new Promise((resolve, reject) => {
        uni.request({
            url: apiUrl + url,
            method: method,
            data: params,
            header: {
                'Content-Type': contentType || 'application/json',
                'Authorization': 'Bearer ' + token
            }
        }).then(resolve).catch(reject);
    });
};

// 响应拦截器函数，处理token相关逻辑及统一的响应处理
const responseInterceptor = (response) => {
    return new Promise((resolve, reject) => {
        const res = response[1];
        if (res.data.accessTokenExpired === "true" || res.data.accessTokenExpired === true || res.statusCode === 401 || res.data.code === -1) {
            // 发起对新接口的调用（刷新token接口）
            uni.request({
                url: apiUrl + 'api/miniProgram/refresh',
                method: 'POST',
                header: {
                    'Content-Type': contentType || 'application/json',
                    'Authorization': refreshToken
                }
            }).then((newResponse) => {
                const newRes = newResponse[1];
                if (newRes.statusCode === 401 || newRes.data.code === -1) {
                    uni.navigateTo({
                        url: '/pages/login/loginSelect'
                    });
                } else {
                    resolve(newRes.data);
                    const access_token = newRes.data.token;
                    const refreshToken = newRes.data.refreshToken;
                    uni.setStorage({
                        key: 'access_token',
                        data: access_token
                    });
                    uni.setStorage({
                        key: 'refreshToken',
                        data: refreshToken
                    });
                }
            }).catch((newError) => {
                console.log(newError);
                const newErr = newError[0];
                reject(newErr);
            });
        } else if (res.data.refreshExpiredCode === true) {
            // 接口出问题，可能是token失效了，返回登陆页
            uni.clearStorage();
            uni.navigateTo({
                url: '/pages/login/loginSelect'
            });
        } else {
            resolve(res.data);
        }
    });
};

// 模拟添加响应拦截器，这里简单地将请求和拦截器逻辑串联起来
const baseRequest = (url, method, params, contentType) => {
    return requestHandler(url, method, params, contentType).then(responseInterceptor);
};

export default {
    baseRequest
};